<?php

namespace app\data\command;

use app\admin\service\FeiShuService;
use app\admin\service\WxWorkService;
use app\data\service\RecordService;
use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;
use think\db\exception\DbException;
use think\facade\Log;

/**
 * 聊天记录解析
 * Class MessageParse
 * @package app\data\command
 */
class NotCompleteRecordAgain extends Command
{
    protected function configure()
    {
        $this->setName('not_complete_record_again');
        $this->setDescription('延期喷漆的未完成订单，每3天重新派一次单');
    }

    /**
     * 延期喷漆的未完成订单，每3天重新派一次单
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        Log::info('延期喷漆的未完成订单，每3天重新派一次单-开始' . date('Y-m-d H:i:s'));

        $this->app->db->name('data_record')->whereIn('paint_status', [-1, 0])->where('analyze_reason', 3)->chunk(100, function ($records) {

            $records = $records->toArray();
            $recordIds = array_column($records, 'id');
            $uuidCityIds = array_column($records, 'uuid_city');
            $recordId2AgainTime = $this->app->db->name('data_record_again_log')->distinct('record_id')->whereIn('record_id', $recordIds)->column('create_at', 'record_id');

            $uuidCity2openId = $this->app->db->name('work_user')->whereIn('id', $uuidCityIds)->column('open_id', 'id');

            foreach ($records as $record) {
                if (empty($recordId2AgainTime[$record['id']]) || $recordId2AgainTime[$record['id']] < date('Y-m-d 0:00:00', strtotime('-3 day'))) {

                    if (!empty($uuidCity2openId[$record['uuid_city']])) {

                        $this->app->db->name('data_record_again_log')->insert([
                            'record_id' => $record['id'],
                            'uuid_city' => $record['uuid_city'],
                            'create_at' => date('Y-m-d H:i:s'),
                        ]);

                        // 发送企业微信消息
                        $message = RecordService::instance()->toForwardText($record, 'city_owner');
                        FeiShuService::instance()->sendMessageTextByUserid($uuidCity2openId[$record['uuid_city']], $message);
                    }
                }
            }

        });

        Log::info('延期喷漆的未完成订单，每3天重新派一次单-结束' . date('Y-m-d H:i:s'));

    }

}